$(function () {
    layui.use(['element', 'table', 'layer', 'laytpl', 'form', 'util'], function () {
        var element = layui.element,
            table = layui.table,
            layer = layui.layer,
            laytpl = layui.laytpl,
            form = layui.form,
            util = layui.util;
        var checkData = [];
        // roleId 0为超级管理员1为管理员2为员工
        let roleList = [
                {roleId: -1, roleStr: '访客', auths: '查询'},
                {roleId: 0, roleStr: '超级管理员', auths: '查询,设置,高级设置'},
                {roleId: 1, roleStr: '管理员', auths: '查询,设置'},
                {roleId: 2, roleStr: '员工', auths: '查询'},
            ];

        //查询全部用户
        getUserData();

        function renderRoleSelect(layero){
            let opt = '<option value="">请选择</option>';
            for (let i = 0; i < roleList.length; i++) {
                opt += `<option value="${roleList[i].roleId}">${roleList[i].roleStr}</option>`
            }
            layero.find('form select').append(opt);
            form.render('select');
        }

        function getUserData() {
            $.ajax({
              type: "GET",
              url: ctx+"/userManger/getAll.do",
              data: {},
              dataType: "json",
              success: function(res){
                  if(res.code === '000000'){
                      let data = res.data;
                      renderTable(data);
                  }else{
                      console.error(res.message);
                  }
              }
            });
        }

        function renderTable(data) {
            var tbHeigth = $('.settings-wrap .table-wrap').height();
            table.render({
                elem: '#account-list',
                id: 'account-list',
                data: data,
                height: tbHeigth,
                title: '用户信息表',
                toolbar: '#toolbar',
                defaultToolbar: [],
                cols: [[ //展示的列
                    {type: 'radio', fixed: 'left'},
                    {field: 'createTime', title: '建立日期',templet: '<div>{{ layui.util.toDateString(d.createTime, "yyyy-MM-dd") }}</div>'},
                    {field: 'userName', title: '用户名'},
                    {field: 'nickName', title: '昵称'},
                    {field: 'roleId', title: '角色',templet: function(d){
                        return roleList.filter(function(item){
                            return item.roleId === d.roleId
                        })[0].roleStr
                     }},
                    {field: 'auths', title: '权限范围',templet: function(d){
                            return roleList.filter(function(item){
                                return item.roleId === d.roleId
                            })[0].auths
                        }},
                    // {field: 'userPwd', title: '密码', hide:true}
                ]],
                page: {
                    layout: ['prev', 'page', 'next', 'count', 'skip', 'limit']
                    , groups: 5 //只显示 5 个连续页码
                    , limit: 15  //每页显示条数
                    , limits: [15, 30, 45, 60]
                },
                loading: true,
                done: function () {
                    $('.layui-table-view > .layui-table-box').height(tbHeigth - 41);
                    $('.layui-table-view > .layui-table-box .layui-table-body').height(tbHeigth - 80);
                }
            });
        }

        //头工具栏事件
        table.on('toolbar(account-list)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id); //获取选中行状态
            switch (obj.event) {
                case 'getCheckData':
                    checkData = checkStatus.data;  //获取选中行数据
                    console.log(checkData);
                    break;
            };
        });

        // 新增
        $('.addBtn').click(function () {
            var layerIdx = layer.open({
                type: 1,
                title: "新增",
                closeBtn: 1,
                anim: 0,
                area: 'auto',
                content: $('#add-tpl').html(),
                success: function (layero, index) {
                    renderRoleSelect(layero);
                }
            });
            form.on('submit(add-param)', function (res) {
                // console.log(res.field); //当前容器的全部表单字段，名值对形式：{name: value}
                let datas = {};
                datas.userName = res.field.userName.trim();
                datas.nickName = res.field.nickName.trim();
                datas.userPwd = res.field.userPwd.trim();
                datas.roleId = res.field.roleId;
                // console.log(datas);
                addUsers(datas);
                layer.close(layerIdx);
                return false;
            });
            $(".add-param button[type='cancel']").click(function () {
                layer.close(layerIdx);
                return false;
            });
        });

        // 编辑
        $('.editBtn').click(function () {
            $('.getCheckData').click();
            if (checkData.length === 1) {
                var layerIdx = layer.open({
                    type: 1,
                    title: "编辑",
                    closeBtn: 1,
                    anim: 0,
                    area: 'auto',
                    content: $('#edit-tpl').html(),
                    success: function (layero, index) {
                        renderRoleSelect(layero);
                        // console.log(checkData[0]);
                        form.val("edit-param", {
                            userId : checkData[0].userId,
                            userName : checkData[0].userName,
                            nickName : checkData[0].nickName,
                            roleId: checkData[0].roleId
                        });
                    }
                });
                form.on('submit(edit-param)', function (res) {
                    // console.log(res.field);//当前容器的全部表单字段，名值对形式：{name: value}
                    let datas = {};
                    datas.userId = res.field.userId;
                    datas.userName = res.field.userName.trim();
                    datas.nickName = res.field.nickName.trim();
                    datas.userPwd = res.field.userPwd.trim() == "" ? null : res.field.userPwd.trim();
                    datas.roleId = res.field.roleId;
                    // console.log(datas);
                    updateUsers(datas);
                    layer.close(layerIdx);
                    return false;
                });
                $(".edit-param button[type='cancel']").click(function () {
                    layer.close(layerIdx);
                    return false;
                });
            } else {
                layer.alert('请选择一条数据')
            }
        });

        // 删除
        $('.delBtn').click(function () {
            $('.getCheckData').click();
            if (checkData.length === 1) {
                var layerIdx = layer.confirm('确认删除?', function (index) {
                    console.log(checkData[0]);
                    deleteUsers(checkData[0].userId);
                    layer.close(index);
                });
            } else {
                layer.alert('请选择一条数据')
            }
        });

        //新增
        function addUsers(data) {
            $.ajax({
                type: "POST",
                url: ctx + "/userManger/insertUser.do",
                data: data,
                dataType: "json",
                success: function (result) {
                    if (result.code == '000000') {
                        getUserData();
                    } else {
                        layer.msg(result.message);
                    }
                }
            });
        }

        // 编辑
        function updateUsers(data) {
            $.ajax({
                type: "POST",
                url: ctx + "/userManger/editUser.do",
                data: data,
                dataType: "json",
                success: function (result) {
                    getUserData();
                    // obj.update(data); //更新table对应值
                }
            });
        }

        //删
        function deleteUsers(userId) {
            $.ajax({
                type: "get",
                url: ctx + "/userManger/deleteUser.do",
                data: {
                    userId: userId
                },
                dataType: "json",
                success: function (result) {
                    if (result.code == '000000') {
                        getUserData();
                    }
                }
            });
        }

        $('#triangle i').click(function(){
            table.resize('account-list');
        });


    });
});


